using UnityEngine;
using System.Collections;

public class FlightControl : MonoBehaviour {
	
	public float RollAgility;
	
	public float PitchAgility;
	
	public float MaxSpeed;
	
	public float ThrottleSensitivity;
	
	public float Speed;
	
	public DieOnCompletion ExplosionPrefab;
	
	public Collider DeathTarget;
	
	public GameObject VisualRoot;
	
	private float Throttle;
	
	private Vector2 MouseZero;
	
	// Use this for initialization
	void Start () {
		MouseZero = (new Rect(0F, 0F, Screen.width, Screen.height)).center;
		Throttle = 0F;
	}
	
	void OnDestroy()
	{
		Application.Quit();
	}
	
	void Disappear()
	{
		VisualRoot.SetActive(false);
	}
	
	void Exit()
	{
		Application.Quit();
	}
	
	void Die()
	{
		Destroy(gameObject);
	}
	
	void Explode()
	{
		GameObject.Instantiate(ExplosionPrefab, transform.position, Quaternion.identity);
		Disappear();
		MaxSpeed = 0F;
		Invoke("Die", 3F);
	}
	
	void RollSelf(float angle)
	{
		transform.localRotation *= Quaternion.AngleAxis(angle, Vector3.forward);
	}
	
	void PitchSelf(float angle)
	{
		transform.localRotation *= Quaternion.AngleAxis(angle, Vector3.right);
	}
	
	float GetSpeed(float throttleDelta)
	{
		return Mathf.Clamp(Throttle += throttleDelta, 0F, 1F) * MaxSpeed;
	}
	
	void OnCollisionEnter(Collision collisionInfo)
	{
		if (collisionInfo.collider == DeathTarget)
			Explode();
	}
	
	// Update is called once per frame
	void Update () {
		Vector2 mouseCurrent = Input.mousePosition;
		float rollDelta = RollAgility * Time.deltaTime;
		float pitchDelta = PitchAgility * Time.deltaTime;
		float throttleDelta = 0F;
		
		// Throttle Up
		if (Input.GetKey(KeyCode.W))
		{
			throttleDelta = ThrottleSensitivity * Time.deltaTime;
		}
		
		// Throttle Down
		else if (Input.GetKey(KeyCode.S))
		{
			throttleDelta = -ThrottleSensitivity * Time.deltaTime;
		}
		
		// Roll Left
		if (Input.GetKey(KeyCode.A))
		{
			RollSelf(-rollDelta);
		}
		
		// Roll Right
		else if (Input.GetKey(KeyCode.D))
		{
			RollSelf(rollDelta);
		}
		
		// Apply pitch & roll
		float deltaY = mouseCurrent.y - MouseZero.y;
		PitchSelf(deltaY * pitchDelta);
		
		// Apply thrust
		transform.Translate(Vector3.forward * (Speed = GetSpeed(throttleDelta)));
	}
}
